﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.ComponentModel;
using Cesave.Domain.PermisosModule.Contracts.Juntas;
using Cesave.Infrastructure.CrossCutting.IoC;
using System.Windows.Forms;
using Cesave.Domain.Core.Entities;

namespace Cesave.DistributedServices.PermisosModule.WindowsHost.ViewModels.Catalogs.Modulos
{
	public partial class ModulosViewModel
	{
		#region Private properties

		/// <summary>
		/// 
		/// </summary>
		private List<Junta> _juntasModulo;

		/// <summary>
		/// 
		/// </summary>
		private Junta _juntaModulo;

		#endregion

		#region Public properties

		/// <summary>
		/// 
		/// </summary>
		public List<Junta> JuntasModulo
		{
			get
			{
				return _juntasModulo;
			}
			private set
			{
				_juntasModulo = value;
				if (_juntasModulo != null)
					RaisePropertyChanged("JuntasModulo");
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public Junta JuntaModulo
		{
			get
			{
				return _juntaModulo;
			}
			private set
			{
				_juntaModulo = value;
				if (_juntaModulo != null)
					RaisePropertyChanged("JuntaModulo");
			}
		}
		
		#endregion

		#region Private methods

		/// <summary>
		/// 
		/// </summary>
		private void LoadJuntasModulo()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					IJuntaService service = IoCFactory.Resolve<IJuntaService>();
					e.Result = service.FindJuntasByEstado(EstadoModulo.EstadoGuid);
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						JuntasModulo = e.Result as List<Junta>;
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		#endregion

		#region Event methods

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void SetCurrentJuntaModulo(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if ((bindingSource != null) && (bindingSource.Current != null))
				JuntaModulo = bindingSource.Current as Junta;
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnJuntasModuloPropertyChanged()
		{
			_view.juntasModuloBindingSource.DataSource = JuntasModulo;
			_view.juntasModuloBindingSource.CurrentChanged += SetCurrentJuntaModulo;
			SetCurrentJuntaModulo(_view.juntasModuloBindingSource, new EventArgs());
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnJuntaModuloPropertyChanged()
		{
		}

		#endregion

	}
}